package com.baizhi.cmfzmanager.controller;

import com.baizhi.cmfzmanager.entity.Guru;
import com.baizhi.cmfzmanager.service.GuruService;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.util.List;

@Controller
public class DownController {

    @Autowired
    private GuruService guruService;

    @RequestMapping("/downGuruTable")
    public void downGuruTable(HttpServletResponse response) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException, IOException {
        List<Guru> gurus = guruService.getAll();
        HSSFWorkbook workbook = new HSSFWorkbook();
        HSSFSheet guru = workbook.createSheet("guru");
        HSSFRow row = guru.createRow(0);
        String[] tablehead={"编号","名字","图片","法号","状态"};
        for(int i=0;i<tablehead.length;i++){
            HSSFCell cell = row.createCell(i);
            cell.setCellValue(tablehead[i]);
        }

        for (int i = 0; i < gurus.size() ; i++) {
            HSSFRow row1 = guru.createRow(i + 1);
            Guru guru1 = gurus.get(i);
            Class<? extends Guru> guru1Class = guru1.getClass();
            Field[] guruFields = guru1Class.getDeclaredFields();
            for (int j=0;j<guruFields.length;j++){
                String fieldname = guruFields[j].getName();
                String getMethodName="get"+fieldname.substring(0,1).toUpperCase()+fieldname.substring(1);
                Method method = guru1Class.getMethod(getMethodName, null);
                Object invoke = method.invoke(guru1, null);
                HSSFCell cell = row1.createCell(j);
                cell.setCellValue(invoke.toString());

            }
        }

        response.setContentType("application/force-download");
        OutputStream out = response.getOutputStream();
        //使用URLEncoder来防止文件名乱码或者读取错误
        response.setHeader("Content-Disposition", "attachment; filename="+ URLEncoder.encode("guru.xls", "utf-8"));
        workbook.write(out);
        out.flush();

    }
}
